package com.ken.common.mysql.utils;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

public class MybatisUtils {

    /**
     * 通过invocation获取实际的目标对象（非代理）
     * @param <T>
     * @return
     */
    public static <T> T getNoProxyTarget(Object target){
        MetaObject invoMetaObject = SystemMetaObject.forObject(target);
        while (invoMetaObject.hasGetter("h")) {
            //说明当前对象是一个代理对象
            target = invoMetaObject.getValue("h.target");
            invoMetaObject = SystemMetaObject.forObject(target);
        }
        //返回实际的对象
        return (T) target;
    }

    /**
     * 获得sql语句中 主查询的from的index下标位置
     * @return
     */
    public static int getFromIndex(int beginIndex, String sql){
        int fromIndex = sql.indexOf("from", beginIndex);
        if (fromIndex == -1) return -1;

        int count = 0;//括号的计数器
        int selectIndex = fromIndex;//当前需要查询括号的位置下标
        int bIndex = -1;//正括号的下标
        while((bIndex = sql.lastIndexOf("(", selectIndex)) != -1){
            count++;
            selectIndex = bIndex - 1;
        }

        selectIndex = fromIndex;//当前需要查询括号的位置下标
        int eIndex = -1;//反括号的下标
        while((eIndex = sql.lastIndexOf(")", selectIndex)) != -1){
            count--;
            selectIndex = eIndex - 1;
        }


        if (count == 0) {
            return fromIndex;
        } else {
            return getFromIndex(fromIndex + 1, sql);
        }
    }

    public static void main(String[] args) {
        String sql = "select a,b,c,(select *,(select * from B where xxx) from B where xxx),(select * from B where xxx),(select * from B where xxx) from table where id = (select xxx from C)";
        int index = MybatisUtils.getFromIndex(0, sql);
        String totalSql = "select count(*) as total " + sql.substring(index);
        System.out.println("-->" + totalSql);
    }
}
